<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- 提示信息区 -->
      <el-alert
      title="注意，只允许为第三级分类设置相关参数"
      type="warning" :closable="false" show-icon>
      </el-alert>
      <!-- 级联选择区 -->
      <el-row>
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader
            v-model="selectCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="CateChange"
            clearable></el-cascader>
        </el-col>
      </el-row>
       <!-- Tabs页签区 -->
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnDisable" @click="addParamsDialogVisible = true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand" label="#">
              <template slot-scope="scope">
                <el-tag closable v-for="(item, i) in scope.row.attr_vals" :key="i" @close="handleColse(i, scope.row)">{{item}}</el-tag>
                <!-- Tag输入文本框 -->
                <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加Tag按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">修改</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisable"  @click="addParamsDialogVisible = true">添加属性</el-button>
          <!-- 静态参数表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand" label="#">
              <template slot-scope="scope">
                <el-tag closable v-for="(item, i) in scope.row.attr_vals" :key="i" @close="handleColse(i, scope.row)">{{item}}</el-tag>
                <!-- Tag输入文本框 -->
                <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加Tag按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">修改</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
     </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog :title="'添加'+titleText" :visible.sync="addParamsDialogVisible" width="50%" @close="addParamsDialogClosed">
        <!-- 内容主体区域 -->
        <el-form :model="addParamsForm" status-icon :rules="addParamsRules" ref="addParamsFormRef" label-width="90px" class="add_user_form">
        <el-form-item :label="titleText + ':'" prop="attr_name">
            <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <!-- 底部按钮区域 -->
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams" >确 定</el-button>
        </span>
    </el-dialog>
    <!-- 修改参数的对话框 -->
    <el-dialog :title="'修改'+titleText" :visible.sync="editParamsDialogVisible" width="50%" @close="editParamsDialogClosed">
        <!-- 内容主体区域 -->
        <el-form :model="addParamsForm" status-icon :rules="addParamsRules" ref="addParamsFormRef" label-width="90px">
        <el-form-item :label="titleText + ':'" prop="attr_name">
            <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <!-- 底部按钮区域 -->
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams" >确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      cateList: [],
      // 级联选择框双向绑定到的数组
      selectCateKeys: [],
      // 指定级联选择器的配置对象
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // tabs选中的名称，默认第一个
      activeName: 'many',
      // 动态参数列表
      manyTableData: [],
      // 静态参数列表
      onlyTableData: [],
      addParamsDialogVisible: false,
      editParamsDialogVisible: false,
      // 添加参数的表单数据对象
      addParamsForm: {
        attr_name: ''
      },
      // 添加参数的校验规则
      addParamsRules: {
        attr_name: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 属性id
      attr_id: ''
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取所有商品分类数据
    async getCateList () {
      const res = await this.$http.get('categories')
      if (res.data.meta.status !== 200) {
        this.$message.error('获取分类数据失败')
      } else {
        this.cateList = res.data.data
      }
    },
    // 级联选择项中变化触发此函数
    CateChange () {
      this.getParamsData()
    },
    // Tabs选项切换处理函数
    handleTabsClick () {
      this.getParamsData()
    },
    // 获取参数列表信息
    async getParamsData () {
      // 证明选中的不是三级分类
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return false
      } else {
        // 根据所选分类id和当前所处的面板获取对应的参数信息
        const res = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
        if (res.data.meta.status !== 200) {
          this.$message.error('获取参数信息失败')
        } else {
          res.data.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
            // 控制Tag文本框的显示与隐藏
            item.inputVisible = false
            // Tag文本框中输入的值
            item.inputValue = ''
          })
          if (this.activeName === 'many') {
            this.manyTableData = res.data.data
          } else {
            this.onlyTableData = res.data.data
          }
        }
      }
    },
    // 关闭添加参数对话框
    addParamsDialogClosed () {
      this.$refs.addParamsFormRef.resetFields()
      this.addParamsForm = {}
      this.addParamsDialogVisible = false
    },
    // 确认添加属性按钮事件
    addParams () {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return false
        const res = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        }
        )
        if (res.data.meta.status !== 201) {
          this.$message.error('添加参数失败')
        } else {
          this.$message.success('添加成功')
          this.addParamsDialogVisible = false
          this.getParamsData()
        }
      })
    },
    // 打开修改对话框
    async showEditDialog (id) {
      this.editParamsDialogVisible = true
      this.attr_id = id
      const res = await this.$http.get(`categories/${this.cateId}/attributes/${this.attr_id}`, { params: { attr_sel: this.activeName } })
      if (res.data.meta.status !== 200) {
        this.$message.error('获取参数信息失败')
      } else {
        this.addParamsForm = res.data.data
      }
    },
    // 关闭修改对话框
    editParamsDialogClosed () {
      this.$refs.addParamsFormRef.resetFields()
      this.addParamsForm = {}
      this.addParamsDialogVisible = false
    },
    // 确定修改参数
    editParams () {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return false
        const res = await this.$http.put(`categories/${this.cateId}/attributes/${this.attr_id}`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.data.meta.status !== 200) {
          this.$message.error('修改数据失败')
        } else {
          this.$message.success('修改成功')
          this.getParamsData()
        }
        this.editParamsDialogVisible = false
      })
    },
    // 删除参数
    deleteParams (id) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
        if (res.data.meta.status !== 200) {
          this.$message.error('删除参数失败')
        } else {
          this.$message.success('已删除')
          this.getParamsData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // Tag标签文本框失去焦点或按下enter键触发
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
      } else {
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        // 发请求将数据添加到数据库中
        this.saveAttrVals(row)
      }
    },
    // 保存Tag标签属性对象
    async saveAttrVals (row) {
      const res = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.data.meta.status !== 200) {
        this.$message.error('修改参数项失败')
      } else {
        this.$message.success('修改成功')
      }
    },
    // 点击按钮展示Tag文本输入框
    showInput (row) {
      row.inputVisible = true
      // 让文本框自动获取焦点
      // this.$nextTick方法的作用是：当页面上元素被重新渲染之后，才会执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除对应的Tag标签
    handleColse (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }

  },

  // 计算属性
  computed: {
    // 如果按钮需要被禁用，则返回true ,不需要禁用则返回false
    isBtnDisable () {
      if (this.selectCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 当前选中的三级分类id
    cateId () {
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[2]
      } else {
        return null
      }
    },
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态参数'
      }
    }

  }

}
</script>

<style lang="less" scoped>
.el-cascader {
    margin-top: 15px;
    margin-left: 15px;
}
.el-tabs {
    margin-top: 15px;
}
.el-tag {
    margin-left: 10px;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
.button-new-tag {
    margin-left: 10px;
}
</style>
